import React, {ReactNode, useEffect, useRef, useState} from "react";
import {Col, Image, Row} from "antd";
import './MyUpload.less';
import {
  ProForm,
  ProFormColorPicker,
  ProFormDigit,
  ProFormInstance,
  ProFormRadio,
  ProFormSlider,
  ProFormText
} from "@ant-design/pro-form";
import {useMount, useRequest, useSetState} from "ahooks";
import {findByDataImageList, posterByDeleteImage, posterEdit} from "@/services/ant-design-pro/poster";
import MyUpload from "./MyUpload";
import {EditOutlined} from "@ant-design/icons";

interface Props {
  id?: number | undefined,
  row?: any | undefined,
  keyNames?: any[] | undefined,
  type?: number | undefined
}

const width = 622;
const height = 1400;
const im = "http://192.168.2.89/ams/static/upload/image/bg/bg.jpg"
const qrcode = "https://img0.baidu.com/it/u=1713971111,2692045543&fm=253&fmt=auto&app=138&f=GIF?w=200&h=200"
const avatar = "https://gd-hbimg.huaban.com/e2530f908adbeceab40757b8f99a7eaf9f35eff816a5a-8UllSs_fw1200"

/* const   imageRect={
  avatar:{
    x:0,y:0,h:30,w:30,url:im
  },
  qrcode:{
    x:0,y:0,h:100,w:100,url:im
  }
}*/

//video
interface PropsImage {
  id: number,
  x: number,
  y: number,
  w: number,
  h: number,
  radius: number,
  url: string,
  type: string,
  name: string,
  keyName: string,
  isRadius: boolean,
  isWH: boolean,
  color: string,
  fontSize: number
}

interface PropsImageType {
  id: number,
  posterId: number,
  imageId: number,
  url: string
}

interface PropsMap {
  keyName: string,
  value: PropsImage
}

const imageRect = {

  "avatar": {
    h: 40,
    name: "头像",
    radius: 100,
    type: "image",
    url: avatar,
    isWH: true,
    w: 40,
    x: 30,
    y: 30,
    keyName: "avatar",

    isRadius: true
  },
  "qrcode": {
    name: "二维码",
    keyName: "qrcode",
    x: 100,
    y: 400,
    h: 150,
    w: 150,
    isWH: true,
    url: qrcode,
    type: "image",
    radius: 0,
    isRadius: false
  },
  "nickname": {
    name: "微信网名",
    keyName: "nickname",
    x: 100,
    y: 45,
    h: 30,
    w: 200,
    isWH: true,
    url: "",
    type: "text",
    radius: 0,
    isRadius: false,
    color: "#ffffff",
    fontSize: 12
  },
  "authName": {
    name: "用户认证名称",
    keyName: "authName",
    x: 100,
    y: 400,
    h: 200,
    w: 200,
    isWH: true,
    url: "",
    type: "text",
    radius: 0,
    isRadius: false,
    color: "#ffffff",
    fontSize: 12

  },
  "invite": {
    name: "代理编号",
    keyName: "invite",
    x: 100,
    y: 400,
    h: 150,
    w: 150,
    isWH: true,
    url: "",
    type: "text",
    radius: 0,
    isRadius: false
    ,
    color: "#ffffff",
    fontSize: 12
  },
  "posterImage": {
    name: "海报图片",
    keyName: "posterImage",
    x: 100,
    y: 300,
    h: 100,
    w: 200,
    isWH: true,
    url: qrcode,
    type: "image",
    radius: 0,
    isRadius: false
  },

  "title": {
    name: "标题",
    keyName: "title",
    x: 100,
    y: 500,
    h: 200,
    w: 200,
    isWH: true,
    url: "",
    type: "text",
    radius: 0,
    isRadius: false
    ,
    color: "#ffffff",
    fontSize: 12
  },
  "price": {
    name: "金额",
    keyName: "price",
    x: 100,
    y: 160,
    h: 200,
    w: 200,
    isWH: true,
    url: "",
    type: "text",
    radius: 0,
    isRadius: false
    ,
    color: "#FF9D4E",
    fontSize: 12
  },
  "goodName": {
    name: "商品名称",
    keyName: "goodName",
    x: 100,
    y: 140,
    h: 200,
    w: 200,
    isWH: true,
    url: "",
    type: "text",
    radius: 0,
    isRadius: false
    ,
    color: "#ffffff",
    fontSize: 12
  },
}


const MyImageEdit: React.FC<Props> = (props) => {
  const {id, keyNames, type} = props;
  const formRef = useRef<ProFormInstance> ();
  const formRef1 = useRef<ProFormInstance> ();

  const canvas = useRef ();
  const [imageData, setImageData] = useState<PropsImageType> ( {id: 0, url: "", posterId: id, imageId: 0, type: type} )
  const [imageDatas, setImageDatas] = useState<PropsImageType[]> ()
  const [typeData, setTypeData] = useState<PropsImage[]> ()


  const [typeDataForm, setTypeDataForm] = useState<any> ( imageRect )
  const [typeDataReact, setTypeDataReact] = useState<ReactNode[]> ()
  const [typeDataReactButton, setTypeDataReactButton] = useState<API.GlobalStatus[]> ()

  const [typeDataSelected, setTypeDataSelected] = useSetState<PropsImage> ( {
    id: 0,
    h: 0,
    name: "",
    radius: 0,
    type: "",
    url: "",
    w: 0,
    x: 0,
    y: 0,
    keyName: "",
    isRadius: false,
    isWH: false,
    fontSize: 12,
    color: "#000000"
  } )
  const [typeDataSelectedCheck, setTypeDataSelectedCheck] = useState<string> ( "" )

//findByDataImageList

  const {
    run: fetchByPageList,
    refresh,
    data: dataList,
    loading,
  } = useRequest ( findByDataImageList, {
    debounceWait: 100,
    manual: true,
  } );

  // initialize the canvas context
  useEffect ( () => {
    let ddd: PropsImage[] = []
    let dddv: API.GlobalStatus[] = []
    if (keyNames != undefined && keyNames.length > 0) {
      console.log ( "keyNames", keyNames )
      for (let i = 0; i < keyNames.length; i++) {
        let imageRectkeyName = keyNames.at ( i )
        console.log ( "imageRectkeyName", imageRectkeyName )
        if (imageRect[imageRectkeyName] != undefined) {
          let item = imageRect[imageRectkeyName];

          ddd.push ( item )
          dddv.push ( {label: item?.name, value: item.keyName} )
        }

      }


      setTypeDataReactButton ( dddv )
      //  console.log ( ddd )
      setTypeData ( ddd )
      //   setTypeDataReact ( dddv )
    }
    // fetchByPageList(id)

  }, [] );

  useMount ( () => {
    fetchByPageList ( id );
  } );
  const onChangeFram = (keyName: string, name: string) => {
    console.log ( 'onChange: ', name );
    let fieldsValue1 = formRef.current?.getFieldsValue ();
    console.log ( 'onChange: ', fieldsValue1 );
    let item = typeDataForm[typeDataSelected?.keyName]
    let item1 = fieldsValue1[typeDataSelected?.keyName]
    if (name != undefined && item?.isWH) {
      if (name == "h") {
        item["w"] = item1?.h
        //   formRef.current?.setFieldsValue ( {w: fieldsValue1.h} )
      }
      if (name == "w") {
        item["h"] = item1?.w
        //     formRef.current?.setFieldsValue ( {h: fieldsValue1.w} )
      }
      let ak = {};
      ak[keyName] = item;
      formRef.current?.setFieldsValue ( ak )
    }

    formRef.current?.setFieldsValue ()
    // ctx.clearRect(typeDataSelected.x,typeDataSelected.y,typeDataSelected.w,typeDataSelected.h);
    let fieldsValue = formRef.current?.getFieldsValue ();

    //   console.log((width/300)/typeDataSelected.x)
    imageRect[typeDataSelected.keyName] = fieldsValue;

    setTypeDataSelected ( imageRect[typeDataSelected.keyName] )
    console.log ( fieldsValue )
    setTypeDataForm ( fieldsValue )

  };


  const getViewItem = (item: PropsImage, index: number) => {
    let fieldsValue = formRef.current?.getFieldsValue ();
    if (item?.type == "image") {
      return fieldsValue?.keyName == item?.keyName ?
        <img className={"canavsDivAvatar"} style={{
          top: fieldsValue?.y,
          left: fieldsValue?.x, borderRadius: fieldsValue?.radius, zIndex: index
        }} src={avatar} width={fieldsValue?.w} height={fieldsValue?.h}/>
        :
        <img className={"canavsDivAvatar"} style={{
          top: imageRect[item?.keyName]?.y,
          left: imageRect[item?.keyName]?.x, borderRadius: imageRect[item?.keyName]?.radius, zIndex: index
        }} src={avatar} width={imageRect[item?.keyName]?.w} height={imageRect[item?.keyName]?.h}/>
    }

    if (item?.type == "text") {

      return fieldsValue?.keyName == item?.keyName ?
        (<span className={"canavsDivAvatar"} style={{
          top: fieldsValue?.y,
          left: fieldsValue?.x, zIndex: index
        }}>{item?.name}</span>)
        :
        (<span className={"canavsDivAvatar"} style={{
          top: imageRect[item?.keyName]?.y,
          left: imageRect[item?.keyName]?.x, zIndex: index
        }}>{item?.name}</span>)
    }
    //  typeDataForm(fieldsValue)

  }
  const getViewItemFeilds = () => {
    let d: ReactNode[] = []
    Object.keyNames ( typeDataForm ).forEach ( (keyName, index) => {
      let item: PropsImage = typeDataForm[keyName];
      //   console.log ( item )
      d.push ( getViewItem ( item, index ) )
    } )
    return d;
  }

  return (<>
    <Row>
      <Col flex="400px">
        <div className={"canavsDiv"}
             style={{
               backgroundImage: `url(${imageData?.url})`,
               backgroundRepeat: "no-repeat",
               backgroundSize: 'contain'
             }}>

          {typeData?.map ( (item, index) => (


            item?.type == "image" ?
              <img className={"canavsDivAvatar"} style={{
                top: typeDataForm[item?.keyName]?.y/2,
                left: typeDataForm[item?.keyName]?.x/2, borderRadius: typeDataForm[item?.keyName]?.radius, zIndex: index
              }} src={avatar} width={typeDataForm[item?.keyName]?.w/2} height={typeDataForm[item?.keyName]?.h/2}/>
              :
              (<span className={"canavsDivAvatar"} style={{
                top: typeDataForm[item?.keyName]?.y/2,
                left: typeDataForm[item?.keyName]?.x/2,
                zIndex: index,
                color: typeDataForm[item?.keyName]?.color,
                fontSize: typeDataForm[item?.keyName]?.fontSize/2
              }}>{item?.name}</span>)

          ) )}
        </div>
      </Col>
      <Col flex="auto">

        <Row>
          <Col flex="auto">
            <div>
              <ProForm<API.GlobalStatus>
                layout={"horizontal"}
                formRef={formRef1}

                submitter={false}
                initialValues={{value: typeDataSelectedCheck}}
                onChange={(e) => {

                }}
              >
                <ProFormRadio.Group
                  name="value"
                  fieldkeyName={"value"}
                  label="Radio.Group"
                  radioType={"button"}
                  options={typeDataReactButton}
                  valuePropName={"value"}
                  formItemProps={{buttonStyle: "solid"}}
                  onChange={(e) => {
                    setTypeDataSelectedCheck ( e?.target?.value )
                    console.log ( e?.target?.value )
                  }}
                />
              </ProForm>
              <ProForm<Object>
                layout={"horizontal"}
                formRef={formRef}
                onFinish={(values) => {
                  //  console.log ( imageData)
                  if (imageData?.imageId > 0) {
                    let param = {
                      data: imageData,
                      posters: Object.values ( values )
                    }
                    posterEdit ( param ).then ( (res) => {
                      console.log ( res );
                    } )
                  }
                }}
                initialValues={imageRect}
                onChange={(e) => {

                }}
              >


                {typeData?.map ( (value, index) => (

                  <>
                    <div style={{display: 'none'}}>

                      <ProFormText hidden={true} name={[value.keyName, "isRadius"]} initialValue={value.isRadius}/>
                      <ProFormText hidden={true} name={[value.keyName, "isWH"]} initialValue={value.isWH}/>
                      <ProFormText hidden={true} name={[value.keyName, "url"]} initialValue={value.url}/>
                      <ProFormText hidden={true} name={[value.keyName, "name"]} initialValue={value.name}/>
                      <ProFormText hidden={true} name={[value.keyName, "keyName"]}/>
                      <ProFormText hidden={true} name={[value.keyName, "type"]}/>
                    </div>

                    {value.type == "image" ?
                      <>
                        <div className={"canvasDiuvv"}>
                          <ProFormDigit hidden={typeDataSelectedCheck != value?.keyName} label={"W"} width={60}
                                        style={{width: '30px'}} name={[value.keyName, "w"]}
                                        onChange={() => onChangeFram ( value.keyName, "w" )}/>
                          <ProFormSlider hidden={typeDataSelectedCheck != value?.keyName} width={"lg"}
                                         name={[value.keyName, "w"]}
                                         max={width}
                                         onChange={() => onChangeFram ( value.keyName, "w" )}/>
                        </div>
                        <div className={"canvasDiuvv"}>
                          <ProFormDigit hidden={typeDataSelectedCheck != value?.keyName} label={"H"} width={60}
                                        style={{width: '30px'}} name={[value.keyName, "h"]}
                                        onChange={() => onChangeFram ( value.keyName, "h" )}/>
                          <ProFormSlider hidden={typeDataSelectedCheck != value?.keyName} name={[value.keyName, "h"]}
                                         max={height}
                                         onChange={() => onChangeFram ( value.keyName, "h" )}/>
                        </div>
                        <div className={"canvasDiuvv"}>
                          <ProFormDigit hidden={typeDataSelectedCheck != value?.keyName} disabled={!value.isRadius}
                                        label={"radius"}
                                        width={60}
                                        style={{width: '30px'}}
                                        name={[value.keyName, "radius"]} onChange={() => onChangeFram ()}/>
                          <ProFormSlider hidden={typeDataSelectedCheck != value?.keyName} disabled={!value.isRadius}
                                         name={[value.keyName, "radius"]} max={100}
                                         onChange={() => onChangeFram ()}/>
                        </div>
                      </>
                      :
                      <>
                        <div className={"canvasDiuvv"}>
                          <ProFormDigit hidden={typeDataSelectedCheck != value?.keyName} label={"fontSize"}
                                        width={100}
                                        style={{width: '70px'}}
                                        name={[value.keyName, "fontSize"]} onChange={() => onChangeFram ()}/>

                        </div>
                        <div className={"canvasDiuvv"}>


                          <ProFormColorPicker hidden={typeDataSelectedCheck != value?.keyName} label={"color"}
                                              width={100}
                                              style={{width: '70px'}}
                                              type={"color"}
                                              name={[value.keyName, "color"]} onChange={() => onChangeFram ()}/>
                        </div>
                      </>
                    }

                    <ProForm.Group>
                      <ProFormDigit hidden={typeDataSelectedCheck != value?.keyName} label={"X"} width={60}
                                    style={{width: '30px'}} name={[value.keyName, "x"]}
                                    onChange={() => onChangeFram ()}/>
                      <ProFormSlider hidden={typeDataSelectedCheck != value?.keyName} name={[value.keyName, "x"]}
                                     max={width}
                                     onChange={() => onChangeFram ()}/>
                    </ProForm.Group><ProForm.Group>
                    <ProFormDigit hidden={typeDataSelectedCheck != value?.keyName} label={"Y"} width={60}
                                  style={{width: '0px'}} name={[value.keyName, "y"]}
                                  onChange={() => onChangeFram ()}/>
                    <ProFormSlider hidden={typeDataSelectedCheck != value?.keyName} name={[value.keyName, "y"]}
                                   max={height}
                                   onChange={() => onChangeFram ()}/>
                  </ProForm.Group>

                  </>

                ) )}

              </ProForm>
            </div>
          </Col>
          <Col flex="300px">
            <><MyUpload width={323} height={700} type={6} onChange={(event, url) => {
              setImageData ( {id: 0, posterId: id, imageId: event, url: url,type:type} )
            }}/></>
          </Col>
        </Row>


      </Col>
    </Row>
    <div style={{padding: "10px"}}>
      {

        dataList?.data?.map ( (item: any, index: any) => (
        <>
          <Image style={{width: "100px", height: "160px", marginBottom: "30px"}} src={item.url}/>
        <div>
          <EditOutlined onClick={()=>{
            posterByDeleteImage(item.id).then((e) =>{
              if(e.success){
                refresh()
              }
            })
          }} />
        </div>
        </>
        )
      )}
    </div>
  </>)
}
export default MyImageEdit


